package com.haotian.aicoder.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.haotian.aicoder.ai.model.HtmlCodeResult;
import com.haotian.aicoder.ai.model.MultiFileCodeResult;
import com.haotian.aicoder.model.enums.CodeGenTypeEnum;
import java.io.File;


@Deprecated
public class CodeFileSaver {

    // 文件保存根目录
    public static final String FILE_SAVE_ROOT_PATH = System.getProperty("user.dir") + "/tmp/code_output";

    /**
     * 保存HTMlCode
     */

    public static File saveHtmlCodeResult(HtmlCodeResult htmlCodeResult){
        String basePath = buildFileSavePath(CodeGenTypeEnum.HTML.getValue());
        writeFile(basePath, "index.html", htmlCodeResult.getHtmlCode());
        return new File(basePath);
    }

    /**
     * 保存MutileFileCode
     */
    public static File saveMultiFileCodeResult(MultiFileCodeResult multiFileCodeResult){
        String basePath = buildFileSavePath(CodeGenTypeEnum.MULTI_FILE.getValue());
        writeFile(basePath,"index.html", multiFileCodeResult.getHtmlCode());
        writeFile(basePath,"script.js", multiFileCodeResult.getJsCode());
        writeFile(basePath,"style.css", multiFileCodeResult.getCssCode());
        return new File(basePath);
    }


    /**
     * 构建文件保存唯一目录 tmp/FILE_SAVE_ROOT_PATH/生成文件类型+雪花id随机数
     */
    private static String buildFileSavePath(String fileType) {
       String uniqueName = StrUtil.format("{}_{}", fileType, IdUtil.getSnowflakeNextId());
       String fileSavePath = StrUtil.format("{}/{}/{}", FILE_SAVE_ROOT_PATH, fileType, uniqueName);
       FileUtil.mkdir(fileSavePath);
       return fileSavePath;
    }

    /**
     * 写入单个文件
     * dirpath 写入的文件路径
     * fileName 文件名
     * 这里再次拼接路径是起到自定义文件名的作用，如index.html等
     */
    private static void writeFile(String dirPath,String filename,String content){
        String newFilePath = dirPath + File.separator + filename;
        FileUtil.writeUtf8String(content,newFilePath);
    }
}
